<template>
  <div class="p-2">
    <!--查询区域-->
    <div class="jeecg-basic-table-form-container">
      <a-form ref="formRef" @keyup.enter.native="searchQuery" :model="queryParam" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-row :gutter="24">
          <a-col :lg="6">
            报表类型：
            <template #label><span title="报表类型">&nbsp;报表类型：</span></template>
            <a-radio-group v-model:value="value1" button-style="solid" @change="handleRadioChange">
              <a-radio-button value="a">应收</a-radio-button>
              <a-radio-button value="b">实收</a-radio-button>
              <a-radio-button value="c">欠收</a-radio-button>
            </a-radio-group>
          </a-col>
          <a-col :lg="6">
            <a-form-item name="communityName">
              <template #label><span title="社区名称">社区名称</span></template>
              <a-select
                v-model:value="queryParam.communityName"
                mode="default"
                style="width: 100%"
                placeholder="请选择社区名称"
                :options="title"
                @change="handleChange"
                :filter-option="handleFilterOption"
                show-search="show-search"
                >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="6">
            <a-form-item name="propertyNumber">
              <template #label><span title="房产编号">房产编号</span></template>
              <a-input placeholder="请输入房产编号" v-model:value="queryParam.propertyNumber"></a-input>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :lg="6">
              <a-form-item name="accountingPeriod">
                <template #label><span title="账期">账期月份</span></template>
<!--                <a-date-picker valueFormat="YYYY-MM-DD" placeholder="请选择账期" v-model:value="queryParam.accountingPeriod" />-->
                <a-date-picker valueFormat="YYYY-MM" v-model:value="queryParam.accountingPeriod" picker="month" />
              </a-form-item>
            </a-col>
            <a-col :lg="6">
              <a-form-item name="paymentMethod">
                <template #label><span title="付款方式">付款方式</span></template>
                <j-category-select placeholder="请选择付款方式" v-model:value="queryParam.paymentMethod" pcode="C03" @change="(value) => handleFormChange('paymentMethod', value)" />
              </a-form-item>
            </a-col>
            <a-col :lg="6">
              <a-form-item>
                 <template #label><span title="缴费时间">缴费时间</span></template>
                 <div style="display: flex">
                   <a-form-item name="paymentTime_begin" style="margin-bottom: 0;">
                     <a-date-picker value-format="YYYY-MM-DD" placeholder="请选择开始日期" v-model:value="queryParam.paymentTime_begin" class="query-group-cust"/>
                   </a-form-item>
                   <span class="query-group-split-cust">~</span>
                   <a-form-item name="paymentTime_end" style="margin-bottom: 0;">
                     <a-date-picker value-format="YYYY-MM-DD" placeholder="请选择结束日期" v-model:value="queryParam.paymentTime_end" class="query-group-cust"/>
                   </a-form-item>
                 </div>
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-col :lg="6">
                <a @click="toggleSearchStatus = !toggleSearchStatus" style="margin-left: 8px">
                  {{ toggleSearchStatus ? '收起' : '展开' }}
                  <Icon :icon="toggleSearchStatus ? 'ant-design:up-outlined' : 'ant-design:down-outlined'" />
                </a>
              </a-col>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!--引用表格-->
<!--    多余的选择行-->
<!--    <BasicTable @register="registerTable" :rowSelection="rowSelection">-->
    <BasicTable @register="registerTable">
      <!--插槽:table标题-->
      <template #tableTitle>
        <strong style="color: purple">对账报表</strong> 账单合计：<strong style="color: purple">{{ zong }}</strong>
        <a-button type="primary" preIcon="ant-design:search-outlined" @click="searchQuery" style="position: absolute; left: 990px; top: -8px">查询</a-button>
        <a-button type="primary" preIcon="ant-design:reload-outlined" @click="searchReset" style="position: absolute; left: 1090px; top: -8px">重置</a-button>
<!--        <a-button type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button>-->
<!--        <a-button type="primary" preIcon="ant-design:export-outlined" @click="onExportXls" style="position: absolute; left: 1190px; top: -8px;"> 导出</a-button>-->
<!--        <j-upload-button  type="primary" preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button>-->
<!--        <a-dropdown v-if="selectedRowKeys.length > 0">-->
<!--          <template #overlay>-->
<!--            <a-menu>-->
<!--              <a-menu-item key="1" @click="batchHandleDelete">-->
<!--                <Icon icon="ant-design:delete-outlined"></Icon>-->
<!--                删除-->
<!--              </a-menu-item>-->
<!--            </a-menu>-->
<!--          </template>-->
<!--          <a-button>批量操作-->
<!--            <Icon icon="mdi:chevron-down"></Icon>-->
<!--          </a-button>-->
<!--        </a-dropdown>-->
        <!-- 高级查询 -->
<!--        <super-query :config="superQueryConfig" @search="handleSuperQuery" />-->
      </template>
      <!--操作栏-->
<!--      <template #action="{ record }">-->
<!--        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)"/>-->
<!--      </template>-->
<!--      <template v-slot:bodyCell="{ column, record, index, text }">-->
<!--      </template>-->
    </BasicTable>
    <!-- 表单区域 -->
<!--    <ReconciliationReportModal ref="registerModal" @success="handleSuccess"></ReconciliationReportModal>-->
  </div>
</template>

<script lang="ts" name="report3-reconciliationReport" setup>
  import { ref, reactive} from 'vue';
  import { BasicTable, } from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { columns, superQuerySchema } from './ReconciliationReport.data';
  import { columns2 } from './ReconciliationReport.data';
  import { columns3 } from './ReconciliationReport.data';
  import { optionslist,total, getImportUrl, getExportUrl } from './ReconciliationReport.api';
  import { useUserStore } from '/@/store/modules/user';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JSearchSelect from '/@/components/Form/src/jeecg/components/JSearchSelect.vue';
  import JCategorySelect from '/@/components/Form/src/jeecg/components/JCategorySelect.vue';
  import { loadCategoryData } from '/@/api/common/api';
  import { getAuthCache, setAuthCache } from '/@/utils/auth';
  import { DB_DICT_DATA_KEY } from '/@/enums/cacheEnum';
  import {onMounted} from "vue";
  import { mapTableTotalSummary } from "@/utils/common/compUtils";
  import { defHttp } from "@/utils/http/axios";



  //下拉搜索框
  const handleChange = (value: string) => {
    console.log(`selected ${value}`);
  };
  const options = ref([]);
  const title = ref([]);
  // 使用 onMounted 钩子，在组件加载时触发获取数据的操作
  onMounted(async () => {
    try {
      // 发送 HTTP 请求到后端接口获取数据
      const response = optionslist();
      response.then((data) => {
        // 在这里处理获取到的数据
        options.value = data;
        console.log('获取到的数据为：', options.value);

        // 提取每个对象的 title 属性的值组成新数组
        title.value = options.value.map(option => ({
          value: option.id,
          label: option.departName,
        }));
        console.log('title获取到的数据为：', title.value);

      }).catch((error) => {
        // 在这里处理获取数据失败的情况
        console.error('获取数据失败：', error);
      });

      // 从响应数据中提取选项列表，假设后端返回的数据是一个包含选项的数组
      // const data = response.data;

      // 更新 options 的值为从后端接口获取的数据
      // options.value = data;
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  });
  const handleFilterOption = (input: string, option: { label: string; value: string }) => {
    return option.label.toLowerCase().includes(input.toLowerCase());
  };
  //*********************************************************************************************

  //报表类型
  const c1 = ref<any>(columns);
  const c = ref(1);
  //接口数据
  const l1Url = ref<any>('/report1/yingshou/list');
  const response = ref(<any>{});
  //选择类型
  const value1 = ref<string>('a');
  //表格数据
  const formSearch = ref((params) => {
    response.value = defHttp.get({ url: l1Url.value, params });
    console.log('response的值为：', response.value);
    return response.value;
  });
  //事件
  const handleRadioChange = (value) => {
    console.log('点击的按钮值为：', value.target.value);
    if (value.target.value === 'a') {
      l1Url.value = '/report1/yingshou/list';
      c1.value = columns;
      c.value = 1;
      // onSummary();
      reload();

      // c1 = columns;
    } else if (value.target.value === 'b') {
      // 实收
      l1Url.value = '/report/reconciliationReport/list';
      c1.value = columns2;
      c.value = 2;
      // onSummary();
      reload();
    } else if (value.target.value === 'c') {
      // 欠收
      l1Url.value = '/report3/qianshou/list';
      c1.value = columns3;
      c.value = 3;
      // onSummary();
      reload();
    }
  };
  //*******************************************************************************

  /**
   * 计算合计
   * @param tableData
   */
  const zong = ref(0);

  // 计算合计
  const realdata = ref({});
  // 定义一个函数，用于从后端接口获取数据并填充到realdata中

  function onSummary() {
    response.value.then((result) => {
      realdata.value = result;
      const publicSanitationValue = result.publicSanitation;
      console.log('publicSanitation 的值为：', publicSanitationValue);
    }).catch((error) => {
      console.error('发生错误：', error);
    });
    const totals: any = {
      _row: '合计',
      _index: '合计',
      publicSanitation:realdata.value.publicSanitation,
      propertyManagement:realdata.value.propertyManagement,
      propertyManagementSix:realdata.value.propertyManagementSix,
      pipelinePressurizationfee:realdata.value.pipelinePressurizationfee,
      parkingServices:realdata.value.parkingServices,
      water:realdata.value.water,
      totalBill:realdata.value.totalBill,
      weiyuejin:realdata.value.weiyuejin,
      zongji:realdata.value.zongji,
    };
    // const totals: any = {
    //   _row: '合计',
    //   _index: '合计',
    //   pipelinePressurizationFee:2,
    //   publicSanitation:2,
    // };
    // 可用工具方法自动计算合计
    zong.value = realdata.value.totalBill;
    return [totals];
  }

  const formRef = ref();
  const queryParam = reactive<any>({});
  const toggleSearchStatus = ref<boolean>(false);
  const registerModal = ref();
  const userStore = useUserStore();
  //注册table数据
  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    tableProps: {
      title: '对账报表',
      columns: c1,
      api: formSearch,
      // api: '/report1/yingshou/list',
      canResize: false,
      useSearchForm: false,
      //操作
      showActionColumn: false,
      // actionColumn: {
      //   width: 120,
      //   fixed: 'right',
      // },
      //序号
      showIndexColumn: true,
      //显示底部合计
      showSummary: true,
      //底部合计计算方法
      summaryFunc: onSummary,
      beforeFetch: (params) => {
        return Object.assign(params, queryParam);
      },
    },
    exportConfig: {
      name: "对账报表",
      url: getExportUrl,
      params: queryParam,
    },
	  importConfig: {
	    url: getImportUrl,
	    success: handleSuccess
	  },
  });
  const [registerTable, { reload, collapseAll, updateTableDataRecord, findTableDataRecord, getDataSource }, { rowSelection, selectedRowKeys }] = tableContext;
  const labelCol = reactive({
    xs:24,
    sm:4,
    xl:6,
    xxl:4
  });
  const wrapperCol = reactive({
    xs: 24,
    sm: 20,
  });

  // 高级查询配置
  const superQueryConfig = reactive(superQuerySchema);

  /**
   * 高级查询事件
   */
  // function handleSuperQuery(params) {
  //   Object.keys(params).map((k) => {
  //     queryParam[k] = params[k];
  //   });
  //   searchQuery();
  // }

  /**
   * 新增事件
   */
  // function handleAdd() {
  //   registerModal.value.disableSubmit = false;
  //   registerModal.value.add();
  // }

  /**
   * 编辑事件
   */
  // function handleEdit(record: Recordable) {
  //   registerModal.value.disableSubmit = false;
  //   registerModal.value.edit(record);
  // }

  /**
   * 详情
   */
  // function handleDetail(record: Recordable) {
  //   registerModal.value.disableSubmit = true;
  //   registerModal.value.edit(record);
  // }

  /**
   * 删除事件
   */
  // async function handleDelete(record) {
  //   await deleteOne({ id: record.id }, handleSuccess);
  // }

  /**
   * 批量删除事件
   */
  // async function batchHandleDelete() {
  //   await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
  // }

  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }

  /**
   * 操作栏
   */
  // function getTableAction(record) {
  //   return [
  //     {
  //       label: '编辑',
  //       onClick: handleEdit.bind(null, record),
  //     },
  //   ];
  // }

  /**
   * 下拉操作栏
   */
  // function getDropDownAction(record) {
  //   return [
  //     {
  //       label: '详情',
  //       onClick: handleDetail.bind(null, record),
  //     }, {
  //       label: '删除',
  //       popConfirm: {
  //         title: '是否确认删除',
  //         confirm: handleDelete.bind(null, record),
  //         placement: 'topLeft',
  //       }
  //     }
  //   ]
  // }

  /**
   * 查询
   */
  function searchQuery() {
    console.log('queryParam的值为:', queryParam);
    reload();
  }

  /**
   * 重置
   */
  function searchReset() {
    formRef.value.resetFields();
    selectedRowKeys.value = [];
    //刷新数据
    reload();
  }




  /**
   * form点击事件 付款方式
   * @param value
   */
  function handleFormChange(key, value) {
    queryParam[key] = value;
  }

  /**
   * 初始化字典配置
   */
  function initDictConfig() {
    loadCategoryData({code:'C03'}).then((res) => {
      if (res) {
        const allDictDate = userStore.getAllDictItems;
        if(!allDictDate['C03']){
          userStore.setAllDictItems({...allDictDate,'C03':res});
        }
        console.log("allDictDate的值为:---------",allDictDate);
      }
    });
  }
  initDictConfig();
</script>

<style lang="less" scoped>
  .jeecg-basic-table-form-container {
    padding: 0;
    .table-page-search-submitButtons {
      display: block;
      margin-bottom: 24px;
      white-space: nowrap;
    }
    .query-group-cust{
      min-width: 100px !important;
    }
    .query-group-split-cust{
      width: 30px;
      display: inline-block;
      text-align: center
    }
  }
</style>
